package com.terra.ns.imp.common.web.response

import com.terra.ns.imp.common.vo.response.PageResult
import com.terra.ns.imp.common.vo.response.ResultBean
import org.springframework.core.MethodParameter
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice

/**
@author qins
@date 2022/5/29
@desc
 */
//@ControllerAdvice  不封装result部分
//@Order(-1000)
class ResponseAdvisor: ResponseBodyAdvice<Any> {
    /**
     * Whether this component supports the given controller method return type
     * and the selected `HttpMessageConverter` type.
     * @param returnType the return type
     * @param converterType the selected converter type
     * @return `true` if [.beforeBodyWrite] should be invoked;
     * `false` otherwise
     */
    override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean {
        return true
    }

    /**
     * Invoked after an `HttpMessageConverter` is selected and just before
     * its write method is invoked.
     * @param body the body to be written
     * @param returnType the return type of the controller method
     * @param selectedContentType the content type selected through content negotiation
     * @param selectedConverterType the converter type selected to write to the response
     * @param request the current request
     * @param response the current response
     * @return the body that was passed in or a modified (possibly new) instance
     */
    override fun beforeBodyWrite(
        body: Any?,
        returnType: MethodParameter,
        selectedContentType: MediaType,
        selectedConverterType: Class<out HttpMessageConverter<*>>,
        request: ServerHttpRequest,
        response: ServerHttpResponse
    ): Any? {
        if(body is ResultBean<*>) {
            val data = body.data
            return if(data is PageResult<*>) {
//                ResultBean<ObjectResult<*>>(body.code, body.msg, ObjectResult(data.dataList, data.pageNo, data.pageSize, data.totalPageCount, data.totalCount))
                body
            } else {
                ResultBean<ObjectResult<*>>(body.code, body.msg, ObjectResult(data))
            }
        }
        return body
    }
}